import React, { useState } from 'react'
import axios from 'axios'
import { Form, Button, Input } from '@nutui/nutui-react'
import { useNavigate } from 'react-router-dom'
import { message } from 'antd'

export default function Plogin() {
    let navgite = useNavigate()
    let login = async (val) => {
        if(code!=mcode) return message.error('验证码错误')
        let res = await axios.post('/szh/plogin', { phone:val.phone})
        if (res.data.code == 200) {
            navgite('/index/home')
            localStorage.setItem('accessToken', res.data.accessToken)
            localStorage.setItem('refreshToken', res.data.refreshToken)
        } else {
            message.error(res.data.msg)
        }
    }
let [codemsg,setcodemsg] = useState('获取验证码')
let [code,setcode] = useState('')
let [mcode,setmcode] = useState('')
let [phone,setPhone] = useState('')
let [num,setnum] = useState(60)
let phoneRegex = /^1[3-9]\d{9}$/
let getcode = async ()=>{
  if(!phoneRegex.test(phone)) return message.error('请输入正确的手机号')
  let res = await axios.post('/szh/get_pcode',{phone:phone})
  if(res.data.code==1) return message.error('操作过于频繁，请稍后再试')
  if(res.data.code==200){
    message.success('验证码已发送')
    setmcode(res.data.pcode)
    setcodemsg(`${num}s`)
    let times = setInterval(()=>{
      setnum(num--)
      setcodemsg(`${num}s`)
      if(num<0){
        clearInterval(times)
        setcodemsg('重新获取')
      }
    },1000)
  }
}
  return (
    <div className='login'>
        <div className='login-form'>
            <h1 className='title'>Welcome to Login</h1>
            <Form
                style={{ width: '90%', borderRadius: ".625rem" }}
                layout='horizontal'
                footer={<>
                    <Button nativeType="submit" block type="primary">
                        登录
                    </Button>
                </>}
                onFinish={(values) => {
                    login(values)
                }}
            >
                <Form.Item validateTrigger="onSubmit" name='phone' label='手机号' rules={[
                    { required: true, message: '请输入手机号' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                ]}>
                    <Input placeholder='请输入手机号' onChange={val=>setPhone(val)} />
                </Form.Item>
                <Form.Item name='code' label='验证码' rules={[
                    { required: true, message: '请输入验证码' }]} 
                >
                    <div style={{display:'flex',alignItems:'center'}}>
                    <Input onChange={val=>{setcode(val);console.log(val);
                    }} placeholder='验证码' />
                    <Button size='mini' type='primary' onClick={getcode} disabled={codemsg!='获取验证码'&&codemsg!='重新获取'}>{codemsg}</Button>              
                    </div>
                </Form.Item>
            </Form>
        </div>
    </div>
  )
}
